cmake_minimum_required(VERSION 3.8)
project(stm32_robot)

# 1. 精确架构检测（使用 uname -m 替代处理器类型匹配）
execute_process(COMMAND uname -m OUTPUT_VARIABLE TARGET_ARCH OUTPUT_STRIP_TRAILING_WHITESPACE)
message(STATUS "Detected Architecture: ${TARGET_ARCH}")

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# 2. 编译器警告选项（通用）
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
    add_compile_options(-Wall -Wextra -Wpedantic -Wno-unused-parameter)
endif()

# 3. 动态适配 ARM 优化（关键修改：移除所有浮点 ABI 选项）
if(TARGET_ARCH MATCHES "aarch64|armv7l|armv6l")
    # 仅对 32 位 ARM 启用安全优化（64 位 ARM 无需 -march 和 -mfloat-abi）
    if(TARGET_ARCH MATCHES "armv7l|armv6l")
        message(STATUS "Enabling safe optimizations for 32-bit ARM")
        add_compile_options(-O2 -march=armv7-a)  # 移除 -mfloat-abi=softfp
    else()
        message(STATUS "No special optimizations for ${TARGET_ARCH}")
    endif()
endif()

# 4. ROS 2 依赖
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(nav_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(std_msgs REQUIRED)
find_package(tf2_ros REQUIRED)
find_package(tf2 REQUIRED)
find_package(tf2_geometry_msgs REQUIRED)
find_package(serial_driver REQUIRED)

# 5. Eigen3
find_package(Eigen3 REQUIRED)

# 6. LibSerial 查找（多路径兼容）
find_library(LIBSERIAL_LIB serial
    PATHS
        /usr/lib/${TARGET_ARCH}-linux-gnu    # ARM 标准路径
        /usr/lib/x86_64-linux-gnu             # PC 路径
        /usr/lib                              # 通用回退
)
if(NOT LIBSERIAL_LIB)
    message(FATAL_ERROR "LibSerial not found! Run: sudo apt install libserial-dev")
else()
    message(STATUS "Found LibSerial: ${LIBSERIAL_LIB}")
endif()

# 7. 头文件路径验证
find_path(LIBSERIAL_INCLUDE_DIR SerialStream.h
    PATHS /usr/include
    PATH_SUFFIXES libserial
    REQUIRED
)

# 8. 构建可执行文件
add_executable(stm32_robot_node
    src/stm32_robot_node.cpp
    src/serial_driver.cpp
)

target_include_directories(stm32_robot_node PRIVATE
    include
    ${EIGEN3_INCLUDE_DIRS}
    ${LIBSERIAL_INCLUDE_DIR}
)

# 9. ROS 2 依赖链接
ament_target_dependencies(stm32_robot_node
    rclcpp
    geometry_msgs
    nav_msgs
    sensor_msgs
    std_msgs
    tf2_ros
    tf2
    tf2_geometry_msgs
    serial_driver
)

# 10. 链接 LibSerial
target_link_libraries(stm32_robot_node
    ${LIBSERIAL_LIB}
)

# 11. 安装规则
install(TARGETS stm32_robot_node
    DESTINATION lib/${PROJECT_NAME}
)

install(DIRECTORY 
    launch
    DESTINATION share/${PROJECT_NAME}
)

install(DIRECTORY 
    config
    DESTINATION share/${PROJECT_NAME}
)

# 12. 测试
if(BUILD_TESTING)
    find_package(ament_lint_auto REQUIRED)
    ament_lint_auto_find_test_dependencies()
endif()

ament_package()